/*
 * Team Huskies:
 * Aakanksha Gaur,
 * Alice Robinson,
 * Paul Winters,
 * Steve Bradshaw
 * Date: June 8th 2011
 */

#include <pthread.h>
#include <stdlib.h>
#include "queue.h"

queue *q_create(void)
{
        queue *q = malloc(sizeof(*q));
        if (!q)
                return NULL;
        q->size = 0;
        q->back = NULL;
        q->front = NULL;
        return q;
}

int q_destroy(queue *q)
{
        if (!q)
                return 0;
        while (!q_isempty(q))
                q_dequeue(q);
        free(q);
        return 1;
}


int q_isempty(queue *q)
{
        if (!q)
                return 1;
        if (!q->front)
                return 1;
        else
                return 0;
}

int q_enqueue(queue *q, qelem_t elem)
{
		//printf("Enqueue Element: %s\n", elem);
        qnode *new = malloc(sizeof(*new));
        if (!new)
				//printf("not new");
                return 0;
        if (!q || !elem)
        {
				//printf("not q or elem");
                free(new);
                return 0;
        }

        //pthread_mutex_lock(&queue_lock);
        new->elem = elem;
        new->next = q->back;
        new->prev = NULL;
        if (q->back)
        {
                q->back->prev = new;
                //printf("q->back->prev");
        }
        q->back = new;
        if (!q->front)
        {
                q->front = new;
                //printf("q->front");
        }
        q->size++;
       //printf("Enqueued Element: %s\n", elem);

        return 1;
}

qelem_t q_dequeue(queue *q)
{
        qnode *prev;
        qelem_t *elem;
        if (q_isempty(q))
        {
				//printf("Returning Null");
                return NULL;
        }
        /*pthread_mutex_lock(&queue_lock);
		if(q_isempty(&q)) {
			pthread_cond_wait(&queue_lock,&not_empty);
		}*/
        prev = q->front->prev;
        elem = q->front->elem;
        free(q->front);
        q->front = prev;
        q->size--;

        //pthread_mutex_unlock(&queue_lock);

        //printf("Dequeue Element: %s\n", elem);

        return elem;
}

/*int push(queue *q, qelem_t elem) {
	int result = 0;
	pthread_mutex_lock(&queue_lock);
	result = q_enqueue(&q, elem);
	pthread_cond_signal(&not_empty);
	pthread_mutex_unlock(&queue_lock);
	return result;
}

qelem_t pop(queue *q) {
	qelem_t result = NULL;

	pthread_mutex_lock(&queue_lock);
	if(q_isempty(&q)) {
		pthread_cond_wait(&queue_lock,&not_empty);
	}
	result = q_dequeue(&q);
	pthread_mutex_unlock(&queue_lock);
	return result;
}*/

